using System;
using CSRedis;

namespace Aurora.Redis.CSRedis;

/// <summary>
/// cs redis 工厂
/// </summary>
public class CSRedisFactory
{
    private readonly string _connection;
    private volatile CSRedisClient _redis;
    private readonly object _lock = new();

    public CSRedisFactory(string connection)
    {
        _connection = connection;
    }

    /// <summary>
    /// 获取实例
    /// </summary>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public CSRedisClient Get()
    {
        if (_redis != null)
        {
            return _redis;
        }

        lock (_lock)
        {
            if (_redis != null)
            {
                _redis.Dispose();
            }

            try
            {
                Console.WriteLine("[Redis创建]进行了CsRedis 的创建");
                _redis = new CSRedisClient(_connection);
                RedisHelper.Initialization(_redis);
            }
            catch (Exception ex)
            {
                throw new Exception("CsRedis服务未启用，请开启该服务," + ex.Message);
            }
        }

        return _redis;
    }
}